package com.yonyou.pmclouds.workflow.util;

import org.springframework.stereotype.Component;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 多任务线程池
 * @param <T>
 * @author zhangzhonghao
 */
@Component
public abstract class BatchExecutor<T> {

    private ThreadPoolExecutor executor = null;

    public void start(){
        if(executor == null){
            synchronized (this){
                if(executor == null) {
                    executor = new ThreadPoolExecutor(5, 10, 30, TimeUnit.SECONDS,
                            new LinkedBlockingDeque<Runnable>(1000));
                }
            }
        }
    }

    public void addTask(T value){
        start();
        executor.execute(new ExecuteWorker(value));
    }

    private class ExecuteWorker implements Runnable{
        private T value;

        public ExecuteWorker(T value){
            this.value = value;
        }

        @Override
        public void run() {
            //执行任务
            executeTaskImpl(value);
        }
    }
    //执行任务抽象类
    public abstract T executeTaskImpl(T value);
}
